{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 1\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [1] for i in train_Y]\n",
    "test_Y = [i + [1] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                _, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                rnn_cells_dec = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells_dec, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = last_state,\n",
    "                                               dtype = tf.float32)\n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-1529fcd0cdad>:11: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-1529fcd0cdad>:28: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-1529fcd0cdad>:31: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:456: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:460: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-7-1529fcd0cdad>:39: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1,  1808, 12696,  8452, 21731, 19939, 30043,  2790, 15632,\n",
       "          14991, 23571, 25971, 29248, 21537, 23904, 16404, 23591, 23368,\n",
       "          21622, 10809, 28732, 24242,  5333,  7897, 21326,  5480, 11738,\n",
       "           3247, 27617, 21457, 25716, 17247, 27192, 17667,  8035, 13181,\n",
       "          10914]],\n",
       " \n",
       "        [[    1, 21336, 21300, 21405, 24213, 15055, 22111, 16214, 13292,\n",
       "           6687, 29254, 15263,  5125, 16368,  6456,  7106, 25411,   672,\n",
       "          21021,  3301, 20996, 29582,  9421, 20400, 21641,  6185, 27892,\n",
       "          18989, 25355,  8685, 29759, 21437, 13441, 31125,  2979, 19404,\n",
       "          12722]],\n",
       " \n",
       "        [[    1,  7926,  5672, 18899, 16910, 17422,  4547, 19039, 29544,\n",
       "          23979, 25975, 28500, 15936, 27635,  8380, 27892,  5190, 21965,\n",
       "           4205, 17290, 13397, 23260, 14851, 30852, 15764, 20643,  8223,\n",
       "           8489, 18448,  6146, 31828, 20410,  9419, 22658,  8652, 21392,\n",
       "            181]],\n",
       " \n",
       "        [[    1, 22546, 10482,  5492,  2655,  7222,   892,  3538,  2658,\n",
       "          11978, 28157, 18782,  1906, 18031,  9122,  7804,  3217, 30528,\n",
       "          30860, 14464,  8526, 27934, 30045, 15255,  7565,  8752,  2292,\n",
       "           5362,  3350, 10977, 20091, 11219, 10431, 19383, 15866, 20297,\n",
       "           6170]],\n",
       " \n",
       "        [[    1, 23687, 26989,  1703, 25570, 11806, 22868, 14454, 21294,\n",
       "           2805, 13434, 25496,    36, 25419, 18132, 22722, 26147, 29806,\n",
       "          28436, 22607, 16378, 28672,  6158,   244,  8290, 15508, 28359,\n",
       "          22409, 10521, 18784, 20865, 17084, 11266, 12177, 30762, 23635,\n",
       "          10597]],\n",
       " \n",
       "        [[    1, 20644,  7521, 13216,  3506, 26905, 28752,  5156,   184,\n",
       "          10623, 21038, 11544,  3863,   281,  9139,  1304, 19312, 10478,\n",
       "           6300, 11178,  1346, 30472, 26665, 20247, 26942, 16522, 22669,\n",
       "          17467, 28752, 12791,  1381,  8063, 17494, 21605, 31581,  2556,\n",
       "          31181]],\n",
       " \n",
       "        [[    1, 30269, 27388,  3168, 17688, 22580,  3315, 28312,  6546,\n",
       "           5370, 20560, 21847,  9305,  1620,  1414,  8663, 27933, 11972,\n",
       "          25492,  8276, 11705,  3050, 31867,    91, 31432,  7096, 30914,\n",
       "          24039, 28127,  2793, 24057, 29349,  1687,  2714, 21329,  8324,\n",
       "          22387]],\n",
       " \n",
       "        [[    1,  6366,  1375,  3043, 26497, 10677,  1857, 19086, 10266,\n",
       "          23383,  4350,  5581, 30528, 15468,  6116, 30563, 18376, 23884,\n",
       "          29387, 19645, 19099,  9928,  9927, 25478,  2669, 11290, 18126,\n",
       "          15327, 17062, 21438,  9476, 13066, 31857, 30285,  7215, 12387,\n",
       "          30039]],\n",
       " \n",
       "        [[    1, 19081,  3477,  8257, 15002,  7448, 23627, 18929, 31372,\n",
       "          16188, 17015,  8075, 23225, 26131,  1227, 14557,  9321, 29432,\n",
       "           3477,  5109,   572,   291, 30918,  7826, 24605, 26347, 26629,\n",
       "           7984, 24024,  3423, 23946, 21702, 25515, 27258,  2879, 23326,\n",
       "          16852]],\n",
       " \n",
       "        [[    1, 21776,  7004, 21758, 26648,  3685,  2535,   336, 23971,\n",
       "           5260, 18235,  8149, 29412, 10299, 30340, 16015,  8964, 25094,\n",
       "          20866,  6141, 10987,  9748, 23864, 23861,  2710, 10120, 26537,\n",
       "          27214, 16598, 26699, 25621, 26998, 20326, 28584,  5452, 23343,\n",
       "          22581]]], dtype=int32), 10.37746, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:04<00:00,  5.13it/s, accuracy=0.0739, cost=7.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.47it/s, accuracy=0.0806, cost=7.29]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.666667, training avg acc 0.073820\n",
      "epoch 1, testing avg loss 7.381644, testing avg acc 0.082898\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:11<00:00,  5.02it/s, accuracy=0.0794, cost=7.14]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.88it/s, accuracy=0.0753, cost=6.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 7.191307, training avg acc 0.088437\n",
      "epoch 2, testing avg loss 7.075523, testing avg acc 0.090813\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:11<00:00,  5.02it/s, accuracy=0.0943, cost=6.79]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.84it/s, accuracy=0.108, cost=6.79] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 6.902056, training avg acc 0.096242\n",
      "epoch 3, testing avg loss 6.903306, testing avg acc 0.098962\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:12<00:00,  5.00it/s, accuracy=0.0896, cost=6.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.88it/s, accuracy=0.102, cost=6.81] \n",
      "minibatch loop:   0%|          | 1/1563 [00:00<05:10,  5.03it/s, accuracy=0.106, cost=6.53]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 6.675107, training avg acc 0.099504\n",
      "epoch 4, testing avg loss 6.816237, testing avg acc 0.099113\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:33<00:00,  4.69it/s, accuracy=0.0957, cost=6.23]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:03<00:00, 10.03it/s, accuracy=0.0753, cost=6.73]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 6.490519, training avg acc 0.101053\n",
      "epoch 5, testing avg loss 6.753743, testing avg acc 0.099890\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:33<00:00,  4.69it/s, accuracy=0.105, cost=6.02] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.86it/s, accuracy=0.086, cost=6.72] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 6.340679, training avg acc 0.103662\n",
      "epoch 6, testing avg loss 6.739402, testing avg acc 0.100558\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:11<00:00,  5.02it/s, accuracy=0.109, cost=5.85] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.76it/s, accuracy=0.086, cost=6.72] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 6.232192, training avg acc 0.105868\n",
      "epoch 7, testing avg loss 6.736602, testing avg acc 0.100681\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:11<00:00,  5.01it/s, accuracy=0.111, cost=5.68] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.82it/s, accuracy=0.086, cost=6.74] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 6.149867, training avg acc 0.107849\n",
      "epoch 8, testing avg loss 6.752310, testing avg acc 0.100701\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:11<00:00,  5.01it/s, accuracy=0.121, cost=5.57] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.93it/s, accuracy=0.0645, cost=6.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 6.084504, training avg acc 0.110086\n",
      "epoch 9, testing avg loss 6.766749, testing avg acc 0.099662\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:25<00:00,  4.80it/s, accuracy=0.127, cost=5.46] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.15it/s, accuracy=0.0699, cost=6.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 6.019907, training avg acc 0.112479\n",
      "epoch 10, testing avg loss 6.781012, testing avg acc 0.100289\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:34<00:00,  4.67it/s, accuracy=0.134, cost=5.37] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.99it/s, accuracy=0.0753, cost=6.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 5.964916, training avg acc 0.114570\n",
      "epoch 11, testing avg loss 6.801286, testing avg acc 0.098891\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.14, cost=5.26]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.94it/s, accuracy=0.0645, cost=6.75]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 5.914329, training avg acc 0.117481\n",
      "epoch 12, testing avg loss 6.812459, testing avg acc 0.100839\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.149, cost=5.22] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.85it/s, accuracy=0.0538, cost=6.83]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 5.865868, training avg acc 0.119487\n",
      "epoch 13, testing avg loss 6.833840, testing avg acc 0.100658\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.159, cost=5.14] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.95it/s, accuracy=0.0645, cost=6.77]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 5.825490, training avg acc 0.121891\n",
      "epoch 14, testing avg loss 6.846583, testing avg acc 0.101458\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.04it/s, accuracy=0.165, cost=5.1] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.97it/s, accuracy=0.0753, cost=6.76]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 5.791389, training avg acc 0.123705\n",
      "epoch 15, testing avg loss 6.865476, testing avg acc 0.101985\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.171, cost=5.05] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.93it/s, accuracy=0.0753, cost=6.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 5.772773, training avg acc 0.123146\n",
      "epoch 16, testing avg loss 6.896725, testing avg acc 0.099580\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.04it/s, accuracy=0.171, cost=4.99]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.99it/s, accuracy=0.0645, cost=6.84]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 5.734043, training avg acc 0.125890\n",
      "epoch 17, testing avg loss 6.915685, testing avg acc 0.100751\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.185, cost=4.96]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.90it/s, accuracy=0.0699, cost=6.75]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 5.696677, training avg acc 0.130331\n",
      "epoch 18, testing avg loss 6.921729, testing avg acc 0.102844\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:10<00:00,  5.03it/s, accuracy=0.175, cost=4.93]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:04<00:00,  9.90it/s, accuracy=0.0806, cost=6.85]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 5.671258, training avg acc 0.132092\n",
      "epoch 19, testing avg loss 6.943552, testing avg acc 0.103010\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [05:09<00:00,  5.05it/s, accuracy=0.187, cost=4.9] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:03<00:00, 10.02it/s, accuracy=0.0645, cost=6.86]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 5.652663, training avg acc 0.132487\n",
      "epoch 20, testing avg loss 6.964406, testing avg acc 0.101766\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [01:35<00:00,  2.39s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6.319555e-05"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
